package com.netty.netty.high.demo5;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LoggingHandler;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;

public class HttpServer {
    //http服务器
  public static void main(String[] args) {


      NioEventLoopGroup boss = new NioEventLoopGroup(1);
      NioEventLoopGroup worker = new NioEventLoopGroup(6);
      new ServerBootstrap()
              .group(boss,worker)
              .channel(NioServerSocketChannel.class)
              .childHandler(new ChannelInitializer<NioSocketChannel>() {

                  @Override
                  protected void initChannel(NioSocketChannel ch) throws Exception {

                      ch.pipeline().addLast(new LoggingHandler());
                      //netty自带的http协议转换
                      ch.pipeline().addLast(new HttpServerCodec());

                      ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){

                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                              //msg有两种类型
                              //class io.netty.handler.codec.http.DefaultHttpRequest
                              //class io.netty.handler.codec.http.LastHttpContent$1

                              if(msg instanceof HttpRequest){

                                  HttpRequest request=(HttpRequest)msg;

                                  //输出响应DefaultFullHttpResponse(HttpVersion version, HttpResponseStatus status)
                                  DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);

                                  String s="hello 2022";
                                  byte b[]=s.getBytes("utf-8");
                                  //从请求头设置响应数据长度，以免浏览器空转
                                  //content_length是io.netty.handler.codec.http包下的类
                                  response.headers().setInt(CONTENT_LENGTH,b.length);

                                  //输出内容
                                  response.content().writeBytes(b);

                                  ctx.channel().writeAndFlush(response);
                              }



                              super.channelRead(ctx, msg);
                          }
                      });
                  }
              }).bind("localhost",8080);


  }
}
